<template>
	<div
		class="game-container report-container "
		:class="[pageType === 1 && 'editPicturePage']"
		:style="pageType === 2 && 'background-color:#fff'"
	>
		<div
			class="editPicturePage-content"
			:style="pageType === 2 && 'width:100%'"
		>
			<div v-if="pageType === 1" class="top-bar">
				<span class="left-title">
					{{
						isEdit
							? $t('common.components.contract')
							: $t('common.components.add_contract')
					}}
				</span>
				<el-button class="right-btn" type="info" @click="back">
					{{ $t('common.back') }}
				</el-button>
			</div>

			<div class="form-container">
				<div class="topform-wrapper">
					<el-form
						ref="topForm"
						v-loading="policyTypeLoading"
						element-loading-spinner="el-icon-loading"
						class="top-form"
						size="normal"
						:model="form"
						label-width="auto"
					>
						<el-form-item
							:label="`${$t('common.agent_number')}:`"
							prop="topForm.signProxyName"
							:rules="rules.topForm.signProxyName"
						>
							<el-input
								v-model.trim="form.topForm.signProxyName"
								:placeholder="$t('common.please_enter')"
								:disabled="isEdit"
								style="width: 80%"
								@blur="getAgentInfo"
							/>
						</el-form-item>
						<el-form-item
							v-if="!isEdit"
							:label="`${$t('common.belong_merchant')}:`"
							prop="topForm.merchantId"
							:rules="rules.topForm.merchantId"
						>
							<el-select
								v-model="form.topForm.merchantId"
								:disabled="
									isEdit ||
										!merchantArr.length ||
										!form.topForm.signProxyName
								"
								:placeholder="
									merchantArr.length > 1
										? $t('common.please_choose')
										: ''
								"
								style="width: 80%"
								@change="selectMerchantHandle"
							>
								<el-option
									v-for="item in merchantArr"
									:key="item.id"
									:label="item.merchantName"
									:value="item.merchantId"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item
							v-if="pageType === 1"
							:label="`${$t('common.components.agent_level')}:`"
							prop="topForm.signProxyLevel"
							:rules="rules.topForm.signProxyLevel"
							:disabled="isEdit"
						>
							<el-input
								v-model.trim="form.topForm.signProxyLevel"
								disabled
								style="width: 80%"
							/>
						</el-form-item>

						<el-form-item
							v-if="pageType === 1"
							:label="`${$t('common.top_agent')}:`"
							prop="topForm.parentProxyName"
							:rules="rules.topForm.parentProxyName"
						>
							<el-input
								v-model.trim="form.topForm.parentProxyName"
								disabled
								:placeholder="
									form.topForm.signProxyLevel === 0
										? $t('common.components.sign_agent')
										: isEdit
										? form.topForm.parentProxyName || '-'
										: ''
								"
								style="width: 80%"
							/>
						</el-form-item>
						<el-form-item
							:label="`${$t('common.components.mode')}:`"
							class="contract-type"
							prop="topForm.contractType"
							:rules="rules.topForm.contractType"
						>
							<template v-if="!isEdit">
								<el-checkbox-group
									v-if="showCheckboxOptions.length"
									v-model="form.topForm.contractType"
									style="width: 80%; text-align: left"
									:disabled="
										!proxyAccountValid || disableCheck
									"
								>
									<!-- todo 一期暂时禁用佣金契约 -->
									<el-checkbox
										disabled
										v-show="
											showCheckboxOptions.includes(
												contractTypeNumber.commission
											)
										"
										:label="contractTypeNumber.commission"
									>
										{{
											$t(
												'common.components.commission_contract'
											)
										}}
									</el-checkbox>
									<el-checkbox
										v-show="
											showCheckboxOptions.includes(
												contractTypeNumber.rebate
											)
										"
										:label="contractTypeNumber.rebate"
									>
										{{
											$t(
												'common.components.rebate_contract'
											)
										}}
									</el-checkbox>
								</el-checkbox-group>
								<el-input
									v-else
									disabled
									:placeholder="
										$t('common.components.no_contract')
									"
									style="width: 80%"
								/>
							</template>
							<el-select
								v-else
								:value="form.topForm.contractType[0]"
								style="width: 80%"
								:placeholder="
									$t('common.components.select_contract')
								"
								:disabled="isEdit"
							>
								<el-option
									v-for="item in contractTypeArr"
									:key="item.description"
									:label="item.description"
									:value="item.code"
								/>
							</el-select>
						</el-form-item>
						<el-form-item
							v-if="
								form.topForm.contractType.includes(
									contractTypeNumber.commission
								)
							"
							:label="
								`${$t('common.components.commission_policy')}:`
							"
							:rules="rules.topForm.commissionPolicyTypeId"
							prop="topForm.commissionPolicyTypeId"
						>
							<el-select
								v-model="form.topForm.commissionPolicyTypeId"
								style="width: 80%"
								clearable
								:placeholder="
									$t('common.components.select_policy')
								"
								:disabled="
									(isEdit ||
										form.topForm.signProxyLevel > 0 ||
										!showCheckboxOptions.length ||
										!proxyAccountValid) &&
										pageType === 1
								"
								@change="onPolicyTypeChange($event, 'select')"
							>
								<template v-for="item in policyTypeArr">
									<el-option
										v-if="
											item.contractType ===
												contractTypeNumber.commission
										"
										:key="item.id"
										:disabled="
											pageType === 2 &&
												item.id + '' ===
													form.topForm
														.oldCommissionPolicyTypeId
										"
										:label="item.policyType"
										:value="item.id"
									/>
								</template>

								<el-option
									:key="0"
									:disabled="
										pageType === 2 &&
											form.topForm
												.oldCommissionPolicyTypeId ===
												'0'
									"
									:label="$t('common.components.custom')"
									:value="0"
								/>
							</el-select>
						</el-form-item>
						<el-form-item
							v-if="
								form.topForm.contractType.includes(
									contractTypeNumber.rebate
								)
							"
							:label="`${$t('common.components.rebate_policy')}:`"
							prop="topForm.rebatePolicyTypeId"
							:rules="rules.topForm.rebatePolicyTypeId"
						>
							<el-select
								v-model="form.topForm.rebatePolicyTypeId"
								style="width: 80%"
								clearable
								:placeholder="
									$t('common.components.select_policy')
								"
								:disabled="
									(isEdit ||
										form.topForm.signProxyLevel > 0 ||
										!showCheckboxOptions.length ||
										!proxyAccountValid) &&
										pageType === 1
								"
								@change="onPolicyTypeChange($event, 'select')"
							>
								<template v-for="item in policyTypeArr">
									<el-option
										v-if="
											item.contractType ===
												contractTypeNumber.rebate
										"
										:key="item.id"
										:disabled="
											pageType === 2 &&
												item.id + '' ===
													form.topForm
														.oldRebatePolicyTypeId
										"
										:label="item.policyType"
										:value="item.id"
									/>
								</template>

								<el-option
									:key="0"
									:disabled="
										pageType === 2 &&
											form.topForm
												.oldRebatePolicyTypeId === '0'
									"
									:label="$t('common.components.custom')"
									:value="0"
								/>
							</el-select>
						</el-form-item>
					</el-form>
				</div>

				<el-tabs
					v-if="showTabsOrRemark"
					v-model="tabsActiveName"
					type="border-card"
					:before-leave="beforeTabChange"
				>
					<el-tab-pane
						v-if="showCommission"
						:label="$t('common.components.commission_contract')"
						name="1"
					>
						<FormTable
							:ref="'tableForm' + contractTypeNumber.commission"
							:custom-form="
								form.topForm.commissionPolicyTypeId === 0
							"
							:top-form="form.topForm"
							:loading.sync="loading"
							:edit-contract-list="editContractList"
							:show-import-btn-group="
								form.topForm.commissionPolicyTypeId !== 0
							"
							:contract-type="contractTypeNumber.commission"
						/>
					</el-tab-pane>
					<el-tab-pane
						v-if="showRebate"
						:label="$t('common.components.rebate_contract')"
						name="2"
					>
						<FormTable
							:ref="'tableForm' + contractTypeNumber.rebate"
							:custom-form="form.topForm.rebatePolicyTypeId === 0"
							:top-form="form.topForm"
							:edit-contract-list="editContractList"
							:loading.sync="loading"
							:show-import-btn-group="
								form.topForm.rebatePolicyTypeId !== 0
							"
							:contract-type="contractTypeNumber.rebate"
						/>
					</el-tab-pane>
				</el-tabs>
				<div v-if="showTabsOrRemark" class="remark-wrapper">
					<el-form
						ref="remarkForm"
						:inline="false"
						size="normal"
						:model="form"
					>
						<el-form-item
							:label="`${$t('common.components.remark')}:`"
							prop="backNote"
							:rules="
								pageType === 1
									? rules.contractEditBackNote
									: rules.editPolicyTypeBackNote
							"
						>
							<el-input
								v-model.trim="form.backNote"
								type="textarea"
								:maxlength="500"
								:placeholder="$t('common.please_enter')"
								:disabled="loading"
								show-word-limit
								style="width: 80%"
								rows="4"
								:minlength="2"
							/>
						</el-form-item>
						<el-form-item style="text-align: center">
							<el-button
								type="primary"
								:disabled="loading"
								size="medium"
								@click="submit"
							>
								<i v-show="loading" class="el-icon-loading" />
								<span>{{ $t('common.confirm') }}</span>
							</el-button>
							<el-button
								icon="el-icon-refresh-left"
								:disabled="loading"
								size="medium"
								@click="reset"
							>
								{{ $t('common.reset') }}
							</el-button>
						</el-form-item>
					</el-form>
				</div>
				<el-empty
					v-if="
						!form.topForm.contractType.length ||
							(!form.topForm.commissionPolicyTypeId &&
								form.topForm.commissionPolicyTypeId !== 0 &&
								(!form.topForm.rebatePolicyTypeId &&
									form.topForm.rebatePolicyTypeId !== 0))
					"
					:description="$t('common.components.please_select_policy')"
				/>
			</div>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import FormTable from '@/components/FormTable'
import { Decimal } from 'decimal.js'
import { rules } from '../../views/agent/agentManage/addAgent/components/rules'
export default {
	components: {
		FormTable
	},
	mixins: [list],
	props: {
		editData: {
			type: Object,
			required: true
		},
		isEdit: {
			type: Boolean,
			default: false
		},
		pageType: {
			type: Number,
			default: 1 // 1 契约管理-编辑契约， 2 代理信息-政策编辑
		}
	},
	data() {
		var validateParentProxyName = (rule, value, callback) => {
			if (this.form.topForm.signProxyLevel !== 0 && value === '') {
				callback(new Error(this.$t('common.components.no_agent_empty')))
			} else {
				callback()
			}
		}
		return {
			policyTypeLoading: true,
			// policyTypeCheckStaus: true,
			loading: false,
			tabsActiveName: '',
			proxyAccountValid: false,
			disableCheck: false,
			policyTypeArr: [],
			showCheckboxOptions: [1, 2],
			form: {
				topForm: {
					contractType: [],
					signProxyName: undefined,
					signProxyLevel: undefined,
					parentProxyName: undefined,
					rebatePolicyTypeId: undefined,
					commissionPolicyTypeId: undefined,
					policyType: {},
					merchantId: ''
				},
				backNote: undefined
			},
			editContractList: [],
			submitLoading: false,
			proxyAccountInfo: {},
			merchantArr: [],
			rules: {
				topForm: {
					signProxyName: rules().parentProxyName,
					merchantId: [
						{
							required: true,
							message: this.$t(
								'common.components.select_merchant'
							),
							trigger: ['blur', 'change']
						}
					],
					signProxyLevel: [
						{
							required: true,
							message: this.$t(
								'common.components.no_agent_empty'
							),
							trigger: ['blur', 'change']
						}
					],
					parentProxyName: [
						{
							required: true,
							validator: validateParentProxyName,
							trigger: ['blur', 'change']
						}
					],
					contractType: [
						{
							type: 'array',
							required: true,
							message: this.$t(
								'common.components.select_contract'
							),
							trigger: 'change'
						}
					],
					commissionPolicyTypeId: [
						{
							required: true,
							message: this.$t(
								'common.components.please_select_agent_policy'
							),
							trigger: 'change'
						}
					],
					rebatePolicyTypeId: [
						{
							required: true,
							message: this.$t(
								'common.components.please_select_rebate_policy'
							),
							trigger: 'change'
						}
					]
				},
				editPolicyTypeBackNote: [
					{
						required: true,
						message: this.$t(
							'common.components.please_input_remark'
						),
						trigger: 'blur'
					},
					{
						min: 2,
						max: 500,
						message: this.$t('common.components.limit_500'),
						trigger: 'blur'
					}
				],
				contractEditBackNote: [
					{
						min: 2,
						max: 500,
						message: this.$t('common.components.limit_500'),
						trigger: 'blur'
					}
				]
			},
			dialogRules: {
				importFormData: {
					templateId: [
						{
							required: true,
							message: this.$t(
								'common.components.select_template'
							),
							trigger: ['change']
						}
					],
					type: [
						{
							required: true,
							message: this.$t(
								'common.components.template_no_empty'
							),
							trigger: 'blur'
						}
					]
				},
				saveFormData: {
					templateName: [
						{
							required: true,
							message: this.$t(
								'common.components.input_template_name'
							),
							trigger: 'blur'
						}
					],
					templateType: [
						{
							required: true,
							message: this.$t(
								'common.components.template_no_empty'
							),
							trigger: 'blur'
						}
					],
					templateDes: [
						{
							required: true,
							message: this.$t(
								'common.components.description_no_empty'
							),
							trigger: 'blur'
						},
						{
							min: 2,
							max: 500,
							message: this.$t('common.components.limit_500'),
							trigger: 'blur'
						}
					]
				}
			}
		}
	},
	computed: {
		accountTypeArr() {
			return this.globalDics.accountType || []
		},
		commissionPolicyTypeIdStatus() {
			if (
				this.form.topForm.commissionPolicyTypeId ||
				this.form.topForm.commissionPolicyTypeId === 0
			) {
				return true
			}
			return false
		},
		rebatePolicyTypeIdStatus() {
			if (
				this.form.topForm.rebatePolicyTypeId ||
				this.form.topForm.rebatePolicyTypeId === 0
			) {
				return true
			}
			return false
		},
		showCommission() {
			if (
				this.form.topForm.contractType.includes(
					this.contractTypeNumber.commission
				) &&
				this.commissionPolicyTypeIdStatus
			) {
				return true
			}
			return false
		},
		showRebate() {
			if (
				this.form.topForm.contractType.includes(
					this.contractTypeNumber.rebate
				) &&
				this.rebatePolicyTypeIdStatus
			) {
				return true
			}
			return false
		},
		showTabsOrRemark() {
			if (
				this.form.topForm.contractType.length &&
				(this.showCommission || this.showRebate) &&
				!this.policyTypeLoading
			) {
				return true
			}
			return false
		},
		showEmpty() {
			if (
				!this.form.topForm.contractType.length ||
				(!this.commissionPolicyTypeIdStatus &&
					!this.rebatePolicyTypeIdStatus)
			) {
				return true
			}
			return false
		},

		// 公用契约类型数字
		contractTypeNumber() {
			return {
				commission: 1,
				rebate: 2
			}
		},
		// 契约模式
		contractTypeArr() {
			return [
				{
					code: 1,
					description: this.$t('common.components.commission')
				},
				{ code: 2, description: this.$t('common.components.rebate') }
			]
		},
		// 当前契约数字
		currentContract() {
			return this.tabsActiveName ? Number(this.tabsActiveName) : undefined
		},
		// 当前契约表格refName
		tableFormRef() {
			return 'tableForm' + this.currentContract
		}
	},
	watch: {
		proxyAccountInfo: function(newVal) {
			if (
				!this.isEdit &&
				(newVal.commissionContractId !== null ||
					newVal.rebateContractId !== null)
			) {
				this.$message.error(
					'代理当前已有契约，暂不可新增契约，请重订契约'
				)
			}
		},
		'form.topForm.contractType': function(valNew) {
			if (Array.isArray(valNew)) {
				if (valNew.length === 1) {
					this.tabsActiveName = String(valNew[0])
				}
			}
		},
		tabsActiveName(val) {
			if (this.form.topForm.signProxyLevel > 0) {
				if (this.tabsActiveName === '1') {
					this.onPolicyTypeChange(
						this.form.topForm.commissionPolicyTypeId,
						'tabs'
					)
				} else {
					this.onPolicyTypeChange(
						this.form.topForm.rebatePolicyTypeId,
						'tabs'
					)
				}
			}
		}
	},
	mounted() {
		// 1 契约管理-编辑契约， 2 代理信息-政策编辑
		if (this.pageType === 2) {
			const merchantId = this.editData.merchantId
			this.getPolicyTypeArr(merchantId)
		} else {
			this.getPolicyTypeArr()
		}

		if (this.isEdit) {
			this.form.topForm = Object.assign({ policyType: {} }, this.editData)
			this.tabsActiveName = String(this.form.topForm.contractType[0])
		}
	},
	methods: {
		getPolicyTypeArr(merchantId) {
			this.policyTypeLoading = true
			const params = {}
			if (merchantId) {
				params.merchantId = merchantId
			}

			this.$api
				.getProxyMinContractPolicyTypeList(params)
				.then((res) => {
					this.policyTypeArr = res.data || []
					this.policyTypeArr.push({
						id: 0,
						policyType: this.$t('common.components.custom')
					})
					if (this.isEdit) {
						this.onPolicyTypeChange(
							this.editData.policyTypeConfigId
						)
						this.loadScaleList()
					}
					this.policyTypeLoading = false
				})
				.catch(() => (this.policyTypeLoading = false))
		},

		onPolicyTypeChange(val, action = null) {
			const policyType = this.policyTypeArr.find(
				(item) => item.id === val
			)
			this.form.topForm.policyType = policyType || {}
			setTimeout(() => {
				if (this.$refs[this.tableFormRef]) {
					if (action === 'select') {
						this.$refs[this.tableFormRef].tableForm = []
					}
					if (action) {
						this.$refs[this.tableFormRef]?.getRebateRatioList()
					}
				}
			}, 100)
		},

		/**
		 * 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
		 */
		beforeTabChange() {
			return new Promise((resolve, reject) => {
				// 校验table表单组件
				this.$refs[this.tableFormRef].$refs['tableForm'].validate(
					(valid) => {
						if (valid) {
							resolve()
						} else {
							reject()
						}
					}
				)
			})
		},

		/**
		 *  异步校验方法
		 */
		validForm(ref) {
			return new Promise((resolve, reject) => {
				ref?.validate((valid) => {
					if (valid) {
						resolve()
					}
				})
			})
		},

		/**
		 * 提交表单
		 */
		submit() {
			// 当前激活的契约表格
			const currentRef = this.$refs[this.tableFormRef]
			const promiseArr = [
				this.validForm(this.$refs['topForm']),
				this.validForm(this.$refs['remarkForm']),
				currentRef && this.validForm(currentRef.$refs['tableForm'])
			]
			// 判断当前契约是否为空

			const commissionContractList = JSON.parse(
				JSON.stringify(this.$refs.tableForm1?.tableForm || [])
			)
			const rebateContractList = JSON.parse(
				JSON.stringify(this.$refs.tableForm2?.tableForm || [])
			)

			if (!commissionContractList.length && !rebateContractList.length) {
				return this.$confirm(
					this.$t('common.components.need_one'),
					this.$t('common.components.tip'),
					{
						confirmButtonText: this.$t('common.confirm'),
						showCancelButton: false,
						type: 'warning'
					}
				)
			}

			Promise.all(promiseArr).then(() => {
				this.loading = true
				commissionContractList.forEach((item) => {
					item.rebateRate = this._decimalToDiv(item.rebateRate)
				})

				rebateContractList.forEach((item) => {
					item.rebateRate = this._decimalToDiv(item.rebateRate)
				})
				const agentInfo = this.agentFilter(this.form.topForm.merchantId)
				const editParams = {
					dataSources: 2,
					commissionContractList,
					rebateContractList,
					id: this.editData.id,
					backNote: this.form.backNote,
					beginRate: this.editData.beginRate,
					accountType: this.editData.accountType,
					contractStatus: this.editData.contractStatus,
					createAccount: this.editData.createAccount,
					effectStatus: this.editData.effectStatus,
					endRate: this.editData.endRate,
					parentProxyId: this.editData.parentProxyId,
					parentProxyName: this.editData.parentProxyName,
					sginType: this.editData.sginType,
					signProxyId: this.editData.signProxyId,
					signProxyLevelId: this.editData.signProxyLevelId,
					signProxyLevel: this.editData.signProxyLevel,
					signProxyName: this.editData.signProxyName,
					merchantId: agentInfo.merchantId,
					merchantName: agentInfo.merchantName
				}

				const createParams = {
					dataSources: 1,
					commissionContractList,
					rebateContractList,
					backNote: this.form.backNote,
					accountType: this.proxyAccountInfo.accountType,
					parentProxyId: this.proxyAccountInfo.parentProxyId,
					parentProxyName: this.proxyAccountInfo.parentProxyName,
					signProxyId: this.proxyAccountInfo.id,
					// signProxyLevelId: this.proxyAccountInfo.proxyLevelId,
					signProxyLevelId: this.proxyAccountInfo.proxyLevel,
					signProxyLevel: this.proxyAccountInfo.proxyLevel,
					signProxyName: this.form.topForm.signProxyName,
					merchantId: agentInfo.merchantId,
					merchantName: agentInfo.merchantName,
					effectStatus: 1
				}

				// 代理详情修改契约政策类型
				const editPolicyTypeParams = {
					dataSources: 2,
					commissionContractList,
					rebateContractList,
					backNote: this.form.backNote,
					id: this.editData.id,
					accountType: this.editData.accountType,
					// contractStatus: this.editData.contractStatus,
					// createAccount: this.editData.createAccount,
					// effectStatus: this.editData.effectStatus,
					// beginRate: this.editData.beginRate,
					// endRate: this.editData.endRate,
					// sginType: this.editData.sginType,
					merchantId: this.editData.merchantId,
					parentProxyId: '0',
					parentProxyName: '',
					signProxyId: this.editData.id,
					signProxyLevelId: '0',
					signProxyLevel: this.editData.signProxyLevel,
					signProxyName: this.editData.userName
				}

				let params
				// 1 契约管理-编辑契约， 2 代理信息-政策编辑
				if (this.pageType === 2) {
					this.getPolicyTypeId(editPolicyTypeParams)
					params = editPolicyTypeParams
					if (this.editData.contractType[0] === 1) {
						params.id = this.editData.commissionContractId
					} else {
						params.id = this.editData.rebateContractId
					}
					params.pageType = 2
				} else {
					if (this.isEdit) {
						if (this.editData.contractType[0] === 1) {
							editParams.commissionPolicyTypeId = this.editData.policyTypeConfigId
						} else {
							editParams.rebatePolicyTypeId = this.editData.policyTypeConfigId
						}
						params = editParams
					} else {
						this.getPolicyTypeId(createParams)
						params = createParams
					}
					params.pageType = 1
				}

				this.$api
					.contractAddOrUpdateAPI(params)
					.then(() => {
						const time = this.pageType === 1 ? 0 : 3000

						setTimeout(() => {
							this.loading = false
							this.$message.success(
								this.$t('common.save_success')
							)
							this.back()
						}, time)
					})
					.catch(() => (this.loading = false))
			})
		},
		/**
		 * 获取政策id
		 */
		getPolicyTypeId(params) {
			if (
				this.form.topForm.commissionPolicyTypeId ||
				this.form.topForm.commissionPolicyTypeId === 0
			) {
				params.commissionPolicyTypeId = this.form.topForm.commissionPolicyTypeId
			}

			if (
				this.form.topForm.rebatePolicyTypeId ||
				this.form.topForm.rebatePolicyTypeId === 0
			) {
				params.rebatePolicyTypeId = this.form.topForm.rebatePolicyTypeId
			}
		},
		/**
		 * 编辑契约时，请求当前契约的条件配置
		 */
		loadScaleList() {
			this.loading = true
			this.editContractList = []
			const params = {
				contractId: this.editData.id,
				contractType: this.form.topForm.contractType[0],
				merchantId: this.form.topForm.merchantId,
				dataSourceType: 2
			}
			this.$api
				.getContractScaleListAPI(params)
				.then((res) => {
					setTimeout(() => {
						this.editContractList = res.data || []
						this.editContractList.forEach((item) => {
							item.rebateRate = this._decimalToMul(
								item.rebateRate
							)
						})
						this.loading = false
						this.$refs[this.tableFormRef]?.getRebateRatioList()
						if (this.isEdit) {
							this.merchantArr = [
								{
									id: this.editData.merchantId,
									merchantId: this.editData.merchantId,
									merchantName: this.merchantFilter(
										this.editData.merchantId
									)
								}
							]
						}
					}, 500)
				})
				.catch(() => {
					this.loading = false
				})
		},

		_decimalToMul(val) {
			return val * 1 === 0 ? 0 : new Decimal(val).mul(100).toNumber()
		},
		_decimalToDiv(val, y) {
			return val * 1 === 0 ? 0 : new Decimal(val).div(y || 100).toNumber()
		},

		// 过滤显示的可选契约类型
		// val: 上级契约模式 0-无契约 1-佣金契约 2-返点契约 3-佣金+返点契约
		// level: 代理层级
		checkContractType(val, level) {
			const proxyHasContract = []
			const commissionNum = this.contractTypeNumber.commission // 1佣金
			const rebateNum = this.contractTypeNumber.rebate // 2返点
			// this.proxyAccountInfo.commissionContractId !== null &&
			// proxyHasContract.push(commissionNum)
			this.proxyAccountInfo.rebateContractId !== null &&
				proxyHasContract.push(rebateNum)
			if (level === 0) {
				if (proxyHasContract.length === 2) {
					this.disableCheck = true
					this.showCheckboxOptions = []
					this.form.topForm.contractType = []
				} else if (proxyHasContract.includes(commissionNum)) {
					this.disableCheck = true
					this.form.topForm.contractType = [rebateNum]
					this.showCheckboxOptions = [rebateNum]
				} else if (proxyHasContract.includes(rebateNum)) {
					this.disableCheck = true
					// this.form.topForm.contractType = [commissionNum]
					this.showCheckboxOptions = [commissionNum]
				} else if (!proxyHasContract.length) {
					this.disableCheck = false
					this.form.topForm.contractType = []
					this.showCheckboxOptions = [commissionNum, rebateNum]
				}
				return
			}
			if (val === 0) {
				this.disableCheck = true
				this.showCheckboxOptions = []
				this.form.topForm.contractType = []
				return
			} else if (val === 1) {
				this.disableCheck = true
				if (!proxyHasContract.includes(commissionNum)) {
					this.form.topForm.contractType = [commissionNum]
					this.showCheckboxOptions = [commissionNum]
				} else {
					this.form.topForm.contractType = []
					this.showCheckboxOptions = []
				}
				return
			} else if (val === 2) {
				this.disableCheck = true
				if (!proxyHasContract.includes(rebateNum)) {
					this.form.topForm.contractType = [rebateNum]
					this.showCheckboxOptions = [rebateNum]
				} else {
					this.form.topForm.contractType = []
					this.showCheckboxOptions = []
				}
				return
			} else if (val === 3) {
				if (
					!proxyHasContract.includes(commissionNum) &&
					!proxyHasContract.includes(rebateNum)
				) {
					this.disableCheck = false
					this.form.topForm.contractType = []
					this.showCheckboxOptions = [commissionNum, rebateNum]
				} else if (
					proxyHasContract.includes(commissionNum) &&
					!proxyHasContract.includes(rebateNum)
				) {
					this.form.topForm.contractType = [rebateNum]
					this.disableCheck = true
					this.showCheckboxOptions = [rebateNum]
				} else if (
					!proxyHasContract.includes(commissionNum) &&
					proxyHasContract.includes(rebateNum)
				) {
					this.form.topForm.contractType = [commissionNum]
					this.disableCheck = true
					this.showCheckboxOptions = [commissionNum]
				} else if (
					proxyHasContract.includes(commissionNum) &&
					proxyHasContract.includes(rebateNum)
				) {
					this.disableCheck = true
					this.form.topForm.contractType = []
					this.showCheckboxOptions = []
				}
			}

			if (this.showCheckboxOptions.length === 0) {
				this.$message.error(this.$t('common.components.no_contract'))
			}
		},
		agentFilter(merchantId) {
			return this.merchantArr.find(
				(item) => item.merchantId === merchantId
			)
		},
		selectMerchantHandle(merchantId) {
			const agentInfo = this.agentFilter(merchantId)
			if (agentInfo) {
				const loading = this.$loading({
					lock: true,
					text: '',
					target: document.getElementsByClassName(
						'form-container'
					)[0],
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.1)'
				})
				const params = {
					userName: agentInfo.userName,
					merchantId: agentInfo.merchantId
				}
				this.$api
					.contractCheckProxyAPI(params)
					.then(async (res) => {
						this.proxyAccountInfo = res.data
						this.proxyAccountValid = true
						this.form.topForm.parentProxyName =
							res.data.parentProxyName
						this.form.topForm.signProxyLevel = res.data.proxyLevel
						if (this.form.topForm.signProxyLevel > 0) {
							this.form.topForm.rebatePolicyTypeId = res.data
								.rebatePolicyTypeId
								? Number(res.data.rebatePolicyTypeId)
								: undefined

							this.form.topForm.commissionPolicyTypeId = res.data
								.commissionPolicyTypeId
								? Number(res.data.commissionPolicyTypeId)
								: undefined
						}

						// 根据上级代理的契约模式判断模式选择
						this.checkContractType(
							res.data.contractModel,
							res.data.proxyLevel
						)
						this.$nextTick(() => {
							this.$refs['topForm'].clearValidate()
						})
						loading.close()
					})
					.catch((error) => {
						if (error.code === 800004) {
							this.$message.error(
								this.$t('common.components.agent_done')
							)
							this.showCheckboxOptions = []
						} else {
							this.showCheckboxOptions = [1, 2]
						}

						this.proxyAccountValid = false
						this.disableCheck = false
						this.initTopFormWithOutSignProxyName()
						this.$nextTick(() => {
							this.$refs['topForm'].clearValidate()
						})
						loading.close()
					})
			}

			this.getPolicyTypeArr(merchantId)
		},
		// 查询需要新增契约账号信息
		getAgentInfo() {
			this.tabsActiveName = ''
			this.form.topForm.merchantId = ''
			if (this.form.topForm.signProxyName) {
				this.initTopFormWithOutSignProxyName()
				this.$nextTick(() => {
					this.$refs['topForm'].clearValidate()
				})
				const loading = this.$loading({
					lock: true,
					text: '',
					target: document.getElementsByClassName(
						'form-container'
					)[0],
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.1)'
				})
				const params = { userName: this.form.topForm.signProxyName }

				this.$api
					.checkProxyDetailAPI(params)
					.then(async (res) => {
						if (res.data && res.data.length) {
							this.merchantArr = res.data
							if (this.merchantArr.length === 1) {
								this.form.topForm.merchantId = this.merchantArr[0][
									'merchantId'
								]
								this.selectMerchantHandle(
									this.form.topForm.merchantId
								)
							}
						} else {
							this.merchantArr = []
							this.$message.error(
								this.$t('common.components.agent_no_exist')
							)
						}
						loading.close()
					})
					.catch((error) => {
						if (error.code === 800004) {
							this.$message.error(
								this.$t('common.components.agent_done')
							)
							this.showCheckboxOptions = []
						} else {
							this.showCheckboxOptions = [1, 2]
						}

						this.proxyAccountValid = false
						this.disableCheck = false
						this.initTopFormWithOutSignProxyName()
						this.$nextTick(() => {
							this.$refs['topForm'].clearValidate()
						})
						loading.close()
					})
			} else {
				this.proxyAccountValid = false
				this.initTopFormWithOutSignProxyName()
				this.$nextTick(() => {
					this.$refs['topForm'].clearValidate()
				})
			}
		},
		initTopFormWithOutSignProxyName() {
			this.form.topForm.parentProxyName = undefined
			this.form.topForm.signProxyLevel = undefined
			this.form.topForm.contractType = []
			this.form.topForm.commissionPolicyTypeId = undefined
			this.form.topForm.rebatePolicyTypeId = undefined
		},
		initTopForm() {
			this.form.topForm = {
				contractType: [],
				signProxyName: undefined,
				signProxyLevel: undefined,
				parentProxyName: undefined,
				rebatePolicyTypeId: undefined,
				commissionPolicyTypeId: undefined,
				merchantId: undefined,
				policyType: {}
			}
			this.$nextTick(() => this.$refs['topForm'].clearValidate())
		},
		back() {
			this.$emit('goback')
		},
		reset() {
			this.$refs['remarkForm'].resetFields()
			if (this.isEdit) {
				this.loadScaleList()
			} else {
				this.initTopForm()
				this.proxyAccountValid = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.editPicturePage {
	background-color: #f5f5f5;
	margin: 0;
	padding: 15px 0 20px;
	min-height: 100vh;
}
.editPicturePage-content {
	width: 80%;
	margin: 0 auto;
	background-color: #fff;
	.top-bar {
		display: flex;
		height: 55px;
		line-height: 55px;
		width: 100%;
		background-color: rgba(0, 0, 0, 1);
		position: relative;
		align-items: center;
		.left-title {
			margin-left: 30px;
			color: #e2e2e2;
			font-size: 16px;
			font-weight: 700;
		}
		.right-btn {
			position: absolute;
			right: 30px;
			color: #fff;
			font-size: 14px;
		}
	}
	.form-container {
		padding: 25px 20px;
		.topform-wrapper {
			width: 100%;
			padding: 35px 0;
			margin-bottom: 30px;
			box-shadow: rgba(88, 88, 88, 0.35) 0px 0px 5px;
			.top-form {
				width: 50%;
				margin: 0 auto;
			}
		}
		.row-class-name {
			color: red;
		}
		.remark-wrapper {
			height: 200px;
			margin: 30px 30% 0;
		}
		::v-deep .el-empty {
			.el-empty__description {
				> p {
					font-size: 20px;
				}
			}
		}
	}
}
</style>
